package com.gmall.batch.gmallbatch.handle.read;


import com.alibaba.fastjson.JSON;
import com.gmall.batch.gmallbatch.model.Message;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.NonTransientResourceException;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.UnexpectedInputException;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author HL.Wu
 * @date 2020/7/6 16:06
 * <p>
 * for:
 */
@Component
@Slf4j
public class FileDataReader implements ItemReader<String> {

    private static final int readCnt = 1; // 批量读取数量
    @Setter
    private List<Message> list = new ArrayList<>();

    private List<Message> list_t = new ArrayList<>();

    @Override
    public String read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
        list_t.clear();
        if(!CollectionUtils.isEmpty(list)){
           // add you need put data to batch read handle.
           if(list.size() >= readCnt){
               list_t = list.subList(0,readCnt);
           }else{
               list_t = new ArrayList<>(list);
               list.clear();
           }
           log.info(" read  :[{}]", JSON.toJSONString(list_t));
           return JSON.toJSONString(list_t);
       }
       return null; // 结束数据读取
    }
}
